import { useUserStore } from "@/store";

const baseURL = "https://pcapi-xiaotuxian-front-devtest.itheima.net";



const interceptor = {
  invoke(xxx) {
    if (!xxx.url.startsWith('https')) {
      xxx.url = baseURL + xxx.url
    }

    uni.showLoading({ title: '请求加载中' })


    // 💥 组件外使用pinia获取store， 注意：执行时机一定要在pinia注册之后
    const store = useUserStore()
    xxx.header = {
      ...xxx.header,
      "source-client": "miniapp",
      Authorization: store.userInfo.token // 💥 
    }
  },
  complete() {
    uni.hideLoading()
  },


}
uni.addInterceptor('request', interceptor)
uni.addInterceptor('uploadFile', interceptor)

export const request = async (arg) => {
  const res = await uni.request(arg)
  if (res.statusCode >= 200 && res.statusCode < 300) {
    return res.data
  }

  if (res.statusCode === 401) {
    uni.navigateTo({ url: '/pages/login/index' })
    return
  }
}